<template>
  <div class="m-component-form-sms">
    <a id="download-model" :href="download.url"></a>
    <!-- form -->
    <div class="form">
      <ul>
        <li class="group icon-box">
          <div class="icon"><img :src="getRequireImg('ShouJi-@2x')"></div>
          <input class="put mobile" type="tel" @blur="iosWechatBlank()" v-model="mobile" placeholder="请输入手机号" maxlength="11" />
        </li>
        <!-- <li class="group">
          <input class="put sms-code" type="tel" @blur="iosWechatBlank" v-model="sms_code" :placeholder="default_config.code_placeholder" maxlength="6"/>
          <button class="btn-get-sms" :class="{ countdown: sms.count !== 0 }" @click="getSms">
            {{ sms.text }}
          </button>
        </li> -->
        <li class="submit">
            <button class="btn-submit" @click="submit()" type="button" >
              立即提现
            </button>
        </li>
        <li v-show="protocol.show" class="group agree">
          <input id="cc2" @click="agreeCheck" type="checkbox" :style="agree.check? getRequireImg('xuan-zhong@2x', 1): ''" />
          <label for="cc2">注册即表明您已阅读并同意</label>
          <span @click.stop="agree.data = 'register';agree.show = true;" > 《{{ protocol.name }}》 </span>
          <span v-if="privacy_protocol.name" @click.stop="agree.data = 'privacy';agree.show = true;" >《{{ privacy_protocol.name }}》</span>
        </li>
      </ul>
    </div>
    <template>
      <x-dialog
        v-model="smsDialog"
        class="sms-dialog-box"
        :dialog-style="{
          'max-width': '100%',
          width: '87%',
          'background-color': '#fff',
          overflow: 'hidden',
          'border-radius': '8px',
        }"
      >
        <div style="text-align: center; font-size: 0.875rem;padding: 31px;">
          <div class="close-btn" @click="closeDialog"><img :src="getRequireImg('cha@2x')" alt=""></div>
          <div class="dialog-title">{{sms.title}}</div>
          <div class="group">
            <input class="put sms-code" type="tel" @blur="iosWechatBlank" v-model="sms_code" :placeholder="default_config.code_placeholder" maxlength="6"/>
            <div class="btn-get-sms" :class="{ countdown: sms.count !== 0 }">
              {{ sms.text }}
            </div>
          </div>
          <div class="submit" @click="noSubmit">确定</div>
          <div @click="reGetSms" class="reGetSms">
            <span>没收到验证码？重新发送</span>
            <img :src="getRequireImg('arror@2x')" alt="">
          </div>
        </div>
      </x-dialog>
    </template>
    
    <div v-show="protocol.show">
      <popup v-model="agree.show" height="100%" :show-mask="false">
        <div class="page-agree-content">
          <protocol-content :data="agree.data" @close="closeAgree" />
        </div>
      </popup>
      
    </div>
    <!-- 微信 -->
    <wechat-mask v-if="WeChat_show"></wechat-mask>
  </div>
</template>

<script>
/*global $ returnCitySN require ClipboardJS wx err process*/
import { isTelPhone, getImg } from "@/service/util.helper";
import { saveCookie } from "../service/util.service";
import { Popup } from "vux";
import WechatMask from "@/components/WechatMask";
import ProtocolContent from "@/components/ProtocolContent";

export default {
  name: "PromoteView",
  components: {
    WechatMask,
    ProtocolContent,
    Popup
  },
  computed: {
  },
  props: {
    data: {
      type: [Object],
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      default_config: {
        phone_placeholder: "请输入手机号",
        code_placeholder: "请输入验证码",
      },
      download: {
        url: "",
        show: false,
      },
      agree: {
        check: true,
        show: false,
        data:'',
      },
      protocol:{
        show: true,
        name: "注册协议"
      },
      privacy_protocol: {
        show: true,
        name: "用户隐私协议",
      },
      mobile: "",
      sms_code: "",
      sms: {
        textBefore: "",
        text: "",
        titleBefore:"请填写验证码",
        reTitle:"验证码已重新发送",
        title:"请填写验证码",
        countTime: 60,
        count: 0,
      },
      WeChat_show: false,
      guide: this.$route.query.id
        ? this.$route.query.id
        : 0,
      auto: false,
      resultVis: false,
      result: {
        status: 0,
        info: "成功",
      },
      alertDialog: false,

      smsDialog: false,
    };
  },
  methods: {
    getRequireImg(name, is64 = 0) {
      let imgObj = {
        name: name,
        is64: is64,
        download_page: this.data.download_page,
        flooring_page: this.data.flooring_page,
      };
      return getImg(imgObj);
    },
    agreeCheck() {
      this.agree.check = !this.agree.check;
    },
    closeAgree(){
      $('.vux-popup-dialog').scrollTop(0)
      this.agree.show = false
    },
    getSms() {
      this.mobile = this.mobile.replace(/(^\s*)|(\s*$)/g, "");
      if (!isTelPhone(this.mobile)) {
        this.$vux.toast.text("请输入正确的手机号", "middle");
        $(".mobile").focus();
        return false;
      }

      this.$vux.loading.show();
      
      this.$http
        .post(`/landing/sms`, {
          phone: this.mobile,
        })
        .then(({ data }) => {
          this.$vux.toast.text(data.msg, "middle");
          this.$vux.loading.hide();
          if (data.code === 200) {
            // 短信倒计时
            this.sms.count = this.sms.countTime;
            let countdown = setInterval(() => {
              this.sms.count--;
              this.sms.text = this.sms.count + "s";
              if (this.sms.count === 0) {
                this.sms.text = this.sms.textBefore;
                clearInterval(countdown);
              }
            }, 1000);
          }
        })
        .catch((err) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络状态不稳定.......！", "middle");
        });
    },
    submit() {
      if (!isTelPhone(this.mobile)) {
        this.$vux.toast.text("请输入正确的手机号", "middle");
        $(".mobile").focus();
        return false;
      }
      if (this.protocol.show && !this.agree.check)
        return this.$vux.toast.text(
          `请同意《${this.protocol.title}》${this.privacy && this.privacy_protocol.name ? `《${this.privacy_protocol.name}》` : ""}协议！`,
          "middle"
        );

      this.smsDialog = true;
      if(this.sms.count == 0){
        this.getSms();
      }
    },
    noSubmit() {
      if (!this.sms_code) {
        this.$vux.toast.text("请输入短信验证码", "middle");
        $(".sms-code").focus();
        return false;
      }
      this.$vux.loading.show();
      let postData = "";
      
      postData = {
        phone: this.mobile,
        yzm: this.sms_code,
        guide: this.guide,
      }
      this.login(undefined, postData);
    },
    login(token, postData) {
      let fData = { ...postData};
      
      this.$http
        .post(`/Landing/register`, fData)
        .then(({ data }) => {
          this.$vux.loading.hide();
          if (data.code === 200) {
            this.$vux.toast.text(data.msg, "middle");
            const user = data.data;
            new Promise((resolve, reject) => {
              // 保存登录信息到cookie
              saveCookie("user", user);
              resolve();
            }).then(() => {
              // 获取/刷新登录信息
              this.$store.dispatch("getUserInfo");
              this.$store.dispatch("loginSuccess", user);
              
              this.getDownload(user)
            });
          } else {
            this.$vux.toast.text(data.msg, "middle");
          }
        })
        .catch((err) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络状态不稳定，请稍后重试！", "middle");
        });
    },
    getUrl(str) {
      console.log(str)
      let url = str.replace(/域名/, window.location.host);
      return url;
    },
    
    iosWechatBlank() {
      // Wechat leave blank compatible
      let ua = this.$router.UA();
      if (ua.ios && ua.weixin) {
        window.scroll(0, 0);
      }
    },
    reGetSms(){
      if(this.sms.count == 0){
        this.sms.title = this.sms.reTitle
        this.getSms();
      }else{
        this.$vux.toast.text("已获取验证码，请稍后再试", "middle");
      }
    },
    closeDialog(){
      this.smsDialog = false;
    },

    getDownload(user){
      this.$http
        .post(`/landing/download`, {})
        .then(({ data }) => {
          this.$vux.loading.hide();
          if (data.code === 200) {
            this.$vux.toast.text(data.msg, "middle");
            
            var url = (this.$router.UA().ios ? data.data.ios : data.data.android);
            sessionStorage.setItem('download_url', url)
            if(user.is_apply == 1){
              this.toProcess()
            }else{
              this.download.url = url
              this.toSuccess()
            }
          } else {
            this.$vux.toast.text(data.msg, "middle");
          }
        })
        .catch((err) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络状态不稳定，请稍后重试！", "middle");
        });
    },
    toSuccess(){
      this.$router.push({
        path:'/success',
      })
    },
    toDownload(){
      if(this.download.url){
        window.location.href = this.download.url
        // $("#download-model")[0].click();
      }
    },
    toProcess(){
      this.$router.push({
        path:'/process/view1',
      })
    },
  },
  watch: {
  },
  created() {
  },
  mounted() {
    if (this.$router.UA().weixin) {
      this.WeChat_show = true;
      return false;
    }
  },
};
</script>

<style lang="scss">

</style>
<style lang="scss" scoped>
.sms-dialog-box{
  position: relative;
  .close-btn{
    position: absolute;
    right: 6px;
    top: 14px;
    z-index: 99;
    width: 22px;
    padding: 3px 4px;
  }
  .dialog-title{
    font-weight: bold;
    font-size: 20px;
    color: #333;
    margin-bottom: 20px;
  }
  .group{
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    margin-bottom: 26px;
    .put{
      height: 52px;
      display: block;
      border: 1px solid #707070;
      border-radius: 4px;
      width: 100%;
      padding-left: 12px;
    }
    .btn-get-sms{
      position: absolute;
      right: 12px;
      color: #AEAEAE;
    }
  }
  .submit{
    background-color: #3478F2;
    color: #fff;
    font-weight: bold;
    text-align: center;
    line-height: 48px;
    width: 166px;
    height: 48px;
    border-radius: 8px;
    font-size: 22px;
    margin: 0 auto 20px;
  }
  .reGetSms{
    display: flex;
    align-items: center;
    justify-content: center;
    span{
      font-size: 14px;
      color: #3478F2;
    }
    img{
      height: 11px;
    }
  }
}
</style>